<template>
  <div class="app-container">
    <!-- 把所有字段都生成了，先删除不要的字段，再做定制化 -->
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true" label-width="120px">
      <el-row>
        <el-col :span="6">
          <el-form-item label="表名" prop="tableNameLike">
            <el-input v-model="queryParams.tableNameLike" placeholder="请输入表名" clearable size="small" style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="描述" prop="descriptionLike">
            <el-input v-model="queryParams.descriptionLike" placeholder="请输入描述" clearable size="small" style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="请求路径" prop="requestMappingLike">
            <el-input v-model="queryParams.requestMappingLike" placeholder="请输入请求路径" clearable size="small" style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="模型状态" prop="isEnable">
            <el-radio-group v-model="queryParams.isEnable">
              <el-radio key="" label="">全部</el-radio>
              <el-radio v-for="dict in isEnableOptions" :key="dict.dictValue" :label="dict.dictValue">{{ dict.dictLabel }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <search-button @click="handleQuery" :perm="['uni:mda:table:info:search']" />
            <reset-button @click="resetQuery" :perm="['uni:mda:table:info:search']" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <add-button @click="handleAdd" :perm="['uni:mda:table:info:insert']" :roleType="['app']" />
      <delete-button @click="handleDelete" :disabled="multiple" :perm="['uni:mda:table:info:delete']" :roleType="['app']" />
      <import-button @click="handleImport" text="迁入"></import-button>
      <right-toolbar v-model:showSearch="showSearch" @query-table="getList" :perm="['uni:mda:table:info:search']" />
    </el-row>

    <!-- 把所有字段都生成了，先删除不要的字段，再做定制化 -->
    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" prop="tableId" :show-overflow-tooltip="true" min-width="100" />
      <el-table-column label="表名" prop="tableName" :show-overflow-tooltip="true" min-width="100" />
      <el-table-column label="描述" prop="description" :show-overflow-tooltip="true" min-width="160" />
      <!-- <el-table-column label="是否主实体" prop="isPrimary" align="center" :show-overflow-tooltip="true" min-width="100">
        <template v-slot="scope">
          <yes-no-tag v-model:value="scope.row.isPrimary"></yes-no-tag>
        </template>
      </el-table-column> -->
      <el-table-column label="仓库名" prop="repository" align="center" :show-overflow-tooltip="true" min-width="100" />
      <el-table-column label="请求路径" prop="requestMapping" :show-overflow-tooltip="true" min-width="100" />
      <el-table-column label="类名" prop="className" :show-overflow-tooltip="true" min-width="200" />
      <el-table-column label="类包名" prop="classPackage" :show-overflow-tooltip="true" min-width="200" />
      <!-- <el-table-column label="子模型ID" prop="subTableId" :show-overflow-tooltip="true" min-width="100" /> -->
      <el-table-column label="模型状态" prop="isEnable" align="center" min-width="100">
        <template #default="scope">
          <el-tag :type="scope.row.isEnable === 'Y' ? 'success' : 'danger'" disable-transitions>
            {{ selectDictLabel(isEnableOptions, scope.row.isEnable) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建者" prop="createBy" align="center" width="120" />
      <el-table-column label="创建时间" prop="createTime" align="center" width="160" />
      <el-table-column label="更新者" prop="updateBy" align="center" width="120" />
      <el-table-column label="更新时间" prop="updateTime" align="center" width="160" />
      <el-table-column label="备注" prop="remark" :show-overflow-tooltip="true" min-width="160" />
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width" fixed="right" v-if="hasRoleType(['app'])">
        <template #default="scope">
          <text-download-button
            @click="handleExport(scope.row)"
            text="迁出"
          />
          <text-add-button
              @click="handleRelateSubModel(scope.row)"
              :perm="['uni:mda:table:info:update']"
              :roleType="['app']" text="关联子模型" />
          <text-edit-button 
            @click="handleAuth(scope.row)" 
            :perm="['uni:mda:table:info:update']" 
            :roleType="['app']" text="数据权限" />
          <text-disable-button
            @click="handleEnableChange(scope.row)"
            :perm="['uni:mda:table:info:update']"
            v-if="scope.row.isEnable == 'Y'"
            :roleType="['app']"
            :title="'是否确认禁用mda模型' + scope.row.tableId + '?'"
          />
          <text-enable-button
            @click="handleEnableChange(scope.row)"
            :perm="['uni:mda:table:info:update']"
            v-if="scope.row.isEnable == 'N'"
            :roleType="['app']"
            :title="'是否确认启用mda模型' + scope.row.tableId + '?'"
          />
          <text-edit-button @click="handleUpdate(scope.row)" :perm="['uni:mda:table:info:update']" :roleType="['app']" />
          <text-delete-button @click="handleDelete(scope.row)" :perm="['uni:mda:table:info:delete']" :roleType="['app']" :title="'是否确认删除mda模型' + scope.row.tableId + '?'" />
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    <!-- 新增或修改对话框 -->
    <el-dialog v-el-drag-dialog :title="editForm.title" :close-on-click-modal="false" v-model="editForm.open" width="50%" append-to-body>
      <el-form ref="formRef" :model="editForm.data" :rules="editForm.rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="数据源" prop="datasourceCode">
              <el-select v-model="editForm.data.datasourceCode" placeholder="请选择数据源" @change="getModelColumn" :disabled="editForm.isModify" filterable clearable>
                <el-option v-for="(op, index) in dataSourceOptions" :key="index" :label="op.datasourceCode" :value="op.datasourceCode" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="数据源实体" prop="tableName" v-if="editForm.data.datasourceCode" required>
              <el-select v-model="editForm.data.tableName" placeholder="请选择数据源实体" @change="handleSelectBranchCom()" :disabled="editForm.isModify" filterable clearable>
                <el-option v-for="(opt, ind) in formEntityList" :key="ind" :label="opt.dictValue" :value="opt.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input v-model="editForm.data.description" placeholder="请输入描述" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="是否主实体" prop="isPrimary">
              <el-select v-model="editForm.data.isPrimary">
                <el-option label="是" value="Y"></el-option>
                <el-option label="否" value="N"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="请求路径" prop="requestMapping">
              <el-input v-model="editForm.data.requestMapping" placeholder="请输入请求路径" clearable>
                <template #prepend>anvil/c/</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="子模型ID" prop="subTableId">
              <el-input v-model="editForm.data.subTableId" placeholder="请输入子模型ID" clearable />
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="editForm.data.remark" placeholder="请输入备注" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-row v-if="editForm.isModify">
              <el-col :span="24" style="text-align: right">
                <reset-button text="刷新" @click="refreshColumn" />
              </el-col>
            </el-row>
            <el-form-item prop="columns">
              <el-table v-loading="loading" :data="editForm.data.columns" @selection-change="handleSelectionChange" max-height="400px">
                <el-table-column label="列名" prop="columnName" :show-overflow-tooltip="true" min-width="100" />
                <el-table-column label="描述" prop="description" :show-overflow-tooltip="true" min-width="160" />
                <el-table-column label="是否查询属性" align="center" prop="isQuery" min-width="120">
                  <template #default="scope">
                    <el-switch v-model="scope.row.isQuery" active-value="Y" inactive-value="N" />
                  </template>
                </el-table-column>
                <el-table-column label="默认值" align="center" prop="defaultValue" :show-overflow-tooltip="true" min-width="100" />
                <el-table-column label="是否为空" align="center" prop="isNull" :show-overflow-tooltip="true" min-width="100">
                  <template #default="scope">
                    <yes-no-tag v-model:value="scope.row.isNull"></yes-no-tag>
                  </template>
                </el-table-column>
                <el-table-column label="是否为删除标志位" align="center" prop="isDelete" :show-overflow-tooltip="true" min-width="160">
                  <template #default="scope">
                    <el-switch v-model="scope.row.isDelete" active-value="Y" inactive-value="N" />
                  </template>
                </el-table-column>
                <el-table-column label="所属存储仓库" prop="tableName" :show-overflow-tooltip="true" min-width="120" />
                <el-table-column label="是否主键" align="center" prop="isPrimaryKey" :show-overflow-tooltip="true" min-width="100">
                  <template #default="scope">
                    <yes-no-tag v-model:value="scope.row.isPrimaryKey"></yes-no-tag>
                  </template>
                </el-table-column>
                <el-table-column label="是否自增" align="center" prop="isAutoIncrement" :show-overflow-tooltip="true" min-width="100">
                  <template #default="scope">
                    <yes-no-tag v-model:value="scope.row.isAutoIncrement"></yes-no-tag>
                  </template>
                </el-table-column>
                <el-table-column label="映射Java属性类型" prop="propertyType" align="center" min-width="160" />
                <el-table-column label="备注" prop="remark" :show-overflow-tooltip="true" min-width="160" />
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <dialog-footer @ok="submitForm" @cancel="cancel" />
      </template>
    </el-dialog>

    <!-- 关联子模型弹窗 -->
    <el-dialog
        :title="subModelDialog.title"
        v-model="subModelDialog.visible"
        width="800px">
      <div class="dialog-toolbar">
        <el-button type="primary" @click="addSubModelRow">添加关联</el-button>
      </div>

      <el-table :data="subModelRelations" border>
        <el-table-column label="子模型" width="300">
          <template #default="{row, $index}">
            <el-select
                v-model="row.subTableId"
                placeholder="请选择子模型"
                @change="val => handleSubModelChange(val, $index)"
            >
              <el-option
                  v-for="item in filteredSubModels"
                  :key="item.tableId"
                  :label="item.tableName"
                  :value="item.tableId"
                  :disabled="item.disabled"
              />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column label="关联字段">
          <template #default="{row}">
            <el-select v-model="row.relationField" placeholder="请选择关联字段">
              <el-option
                  v-for="col in row.fieldOptions"
                  :key="col.columnId"
                  :label="col.columnName"
                  :value="col.columnId"/>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="80">
          <template #default="{$index}">
            <el-button link type="danger" @click="removeSubModelRow($index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <el-button @click="subModelDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveSubModelRelation">保存</el-button>
      </template>
    </el-dialog>

    <!-- 配置授权 -->
    <drag-dialog :title="configAuthPage.title" :close-on-click-modal="false" v-model="configAuthPage.open" width="60%" append-to-body @close="cancelConfigAuth">
      <span>开启授权使用：</span>
      <el-switch :model-value="configAuthPage.enableAuth" active-value="Y" inactive-value="N" @change="handleEnableAuth" />
      <el-tabs v-if="configAuthPage.enableAuth === 'Y'" type="border-card" v-model="configAuthPage.dataParams.authType" @tab-click="handleAuthType">
        <el-tab-pane label="人员授权" name="01">
          <el-form :model="configAuthPage.userParams" :inline="true" label-width="100px">
            <el-form-item label="登录名：">
              <el-input v-model="configAuthPage.userParams.loginNameLike" clearable size="default" style="width: 200px" />
            </el-form-item>
            <el-form-item label="用户姓名：">
              <el-input v-model="configAuthPage.userParams.userNameLike" clearable size="default" style="width: 200px" />
            </el-form-item>
            <el-form-item>
              <search-button @click="handleAuthQuery" />
              <reset-button @click="resetAuthQuery" />
            </el-form-item>
          </el-form>
          <br />
          <el-row :gutter="10" class="mb8">
            <add-button @click="openAuthDialog" text="选择" />
            <delete-button @click="handleAuthDeleteBatch" :disabled="configAuthPage.selectAuthObjectList.length == 0" text="删除"></delete-button>
          </el-row>
          <el-table :data="configAuthPage.authUserDataList" @selection-change="handleAuthSelectionChange" border>
            <el-table-column type="selection" width="55" />
            <el-table-column label="数据权限范围" align="center" prop="dataScope" min-width="120">
              <template #default="scope">
                {{ selectDictLabel(dataScopeOptions, scope.row.dataScope) }}
              </template>
            </el-table-column>
            <el-table-column label="登录名" align="center" prop="loginName" min-width="120" />
            <el-table-column label="用户姓名" align="center" prop="userName" min-width="120" />
            <el-table-column label="公司/部门" align="center" min-width="120">
              <template #default="scope">
                {{ (scope.row.companyName || '-') + ' / ' + (scope.row.deptName || '-') }}
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" min-width="120">
              <template #default="scope">
                <el-popover v-if="scope.row.status === '2'" placement="top-start" width="240" trigger="hover" title="用户已锁定">
                  <template #reference>
                    <el-tag type="warning">锁定</el-tag>
                  </template>
                </el-popover>
                <el-tag v-else :type="scope.row.status === '0' ? 'success' : 'danger'" disable-transitions>
                  {{ scope.row.status === '0' ? '正常' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" min-width="100" fixed="right">
              <template #default="scope">
                <text-delete-button @click="handleAuthDelete(scope.row)" :title="'是否确认删除' + scope.row.loginName + '?'" />
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="configAuthPage.total > 0"
            :total="configAuthPage.total"
            v-model:page="configAuthPage.userParams.pageNum"
            v-model:limit="configAuthPage.userParams.pageSize"
            @pagination="getUserAuthList"
          />
        </el-tab-pane>
        <el-tab-pane label="部门授权" name="02">
          <el-form :model="configAuthPage.deptParams" :inline="true" label-width="100px">
            <el-form-item label="部门名称：">
              <el-input v-model="configAuthPage.deptParams.deptNameLike" clearable size="default" style="width: 200px" />
            </el-form-item>
            <el-form-item>
              <search-button @click="handleAuthQuery" />
              <reset-button @click="resetAuthQuery" />
            </el-form-item>
          </el-form>
          <br />
          <el-row :gutter="10" class="mb8">
            <add-button @click="openAuthDialog" text="选择" />
            <delete-button @click="handleAuthDeleteBatch" :disabled="configAuthPage.selectAuthObjectList.length == 0" text="删除"></delete-button>
          </el-row>
          <el-table :data="configAuthPage.authDeptDataList" @selection-change="handleAuthSelectionChange" border>
            <el-table-column type="selection" width="55" />
            <el-table-column label="数据权限范围" align="center" prop="dataScope" min-width="120">
              <template #default="scope">
                {{ selectDictLabel(dataScopeOptions, scope.row.dataScope) }}
              </template>
            </el-table-column>
            <el-table-column label="部门名称" align="center" prop="deptName" min-width="120" />
            <el-table-column label="部门编码" align="center" prop="deptCode" min-width="120" />
            <el-table-column label="简称" align="center" prop="deptShortname" min-width="120" />
            <el-table-column label="状态" align="center" min-width="120">
              <template #default="scope">
                <el-tag :type="scope.row.status === 'Y' ? 'success' : 'danger'" disable-transitions>
                  {{ scope.row.status === 'Y' ? '正常' : '停用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" min-width="100" fixed="right">
              <template #default="scope">
                <text-delete-button @click="handleAuthDelete(scope.row)" :title="'是否确认删除' + scope.row.deptName + '?'" />
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="configAuthPage.total > 0"
            :total="configAuthPage.total"
            v-model:page="configAuthPage.deptParams.pageNum"
            v-model:limit="configAuthPage.deptParams.pageSize"
            @pagination="getDeptAuthList"
          />
        </el-tab-pane>
        <el-tab-pane label="公司授权" name="03">
          <el-form :model="configAuthPage.companyParams" :inline="true" label-width="100px">
            <el-form-item label="公司名称：">
              <el-input v-model="configAuthPage.companyParams.companyNameLike" clearable size="default" style="width: 200px" />
            </el-form-item>
            <el-form-item>
              <search-button @click="handleAuthQuery" />
              <reset-button @click="resetAuthQuery" />
            </el-form-item>
          </el-form>
          <br />
          <el-row :gutter="10" class="mb8">
            <add-button @click="openAuthDialog" text="选择" />
            <delete-button @click="handleAuthDeleteBatch" :disabled="configAuthPage.selectAuthObjectList.length == 0" text="删除"></delete-button>
          </el-row>
          <el-table :data="configAuthPage.authCompanyDataList" @selection-change="handleAuthSelectionChange" border>
            <el-table-column type="selection" width="55" />
            <el-table-column label="数据权限范围" align="center" prop="dataScope" min-width="120">
              <template #default="scope">
                {{ selectDictLabel(dataScopeOptions, scope.row.dataScope) }}
              </template>
            </el-table-column>
            <el-table-column label="公司名称" align="center" prop="companyName" min-width="120" />
            <el-table-column label="公司编码" align="center" prop="companyCode" min-width="120" />
            <el-table-column label="简称" align="center" prop="companyShortname" min-width="120" />
            <el-table-column label="状态" align="center" min-width="120">
              <template #default="scope">
                <el-tag :type="scope.row.status === 'Y' ? 'success' : 'danger'" disable-transitions>
                  {{ scope.row.status === 'Y' ? '正常' : '停用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" min-width="100" fixed="right">
              <template #default="scope">
                <text-delete-button @click="handleAuthDelete(scope.row)" :title="'是否确认删除' + scope.row.companyName + '?'" />
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="configAuthPage.total > 0"
            :total="configAuthPage.total"
            v-model:page="configAuthPage.companyParams.pageNum"
            v-model:limit="configAuthPage.companyParams.pageSize"
            @pagination="getCompanyAuthList"
          />
        </el-tab-pane>
        <el-tab-pane label="角色授权" name="04">
          <el-form :model="configAuthPage.roleParams" :inline="true" label-width="100px">
            <el-form-item label="角色名称：">
              <el-input v-model="configAuthPage.roleParams.roleNameLike" clearable size="default" style="width: 200px" />
            </el-form-item>
            <el-form-item>
              <search-button @click="handleAuthQuery" />
              <reset-button @click="resetAuthQuery" />
            </el-form-item>
          </el-form>
          <br />
          <el-row :gutter="10" class="mb8">
            <add-button @click="openAuthDialog" text="选择" />
            <delete-button @click="handleAuthDeleteBatch" :disabled="configAuthPage.selectAuthObjectList.length == 0" text="删除"></delete-button>
          </el-row>
          <el-table :data="configAuthPage.authRoleDataList" @selection-change="handleAuthSelectionChange" border>
            <el-table-column type="selection" width="55" />
            <el-table-column label="数据权限范围" align="center" prop="dataScope" min-width="120">
              <template #default="scope">
                {{ selectDictLabel(dataScopeOptions, scope.row.dataScope) }}
              </template>
            </el-table-column>
            <el-table-column label="角色名称" align="center" prop="roleName" min-width="120" />
            <el-table-column label="角色类型" prop="roleType" align="center" min-width="100">
              <template #default="scope">
                <el-tooltip
                  v-if="scope.row.roleType === '0'"
                  content="【系统内置】授权后可拥有所有菜单所有按钮权限"
                  placement="right-start"
                  effect="light"
                >
                  <el-tag type="danger">超级角色</el-tag>
                </el-tooltip>
                <el-tooltip
                  v-else-if="scope.row.roleType === '1'"
                  placement="right-start"
                  effect="light"
                >
                  <template #content>
                    <div
                    >【系统内置】只有配置类型角色授权后才可以做系统的配置管理<br />配置管理包括角色、菜单、字典、参数和ZCache等管理权限</div
                    >
                  </template>
                  <el-tag type="warning">配置角色</el-tag>
                </el-tooltip>
                <el-tooltip
                  v-else-if="scope.row.roleType === '2'"
                  placement="right-start"
                  effect="light"
                >
                  <template #content>
                    <div
                    >用于实际业务系统的功能应用操作<br />即使进行菜单按钮授权也无法操作以上配置管理功能</div
                    >
                  </template>
                  <el-tag type="success" effect="light">应用角色</el-tag>
                </el-tooltip>
                <el-tag v-else>{{ scope.row.roleType }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="角色权限字符串" align="center" prop="roleKey" min-width="120" />
            <el-table-column label="状态" align="center" min-width="120">
              <template #default="scope">
                <el-tag :type="scope.row.status === 'Y' ? 'success' : 'danger'" disable-transitions>
                  {{ scope.row.status === 'Y' ? '正常' : '停用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" min-width="100" fixed="right">
              <template #default="scope">
                <text-delete-button @click="handleAuthDelete(scope.row)" :title="'是否确认删除' + scope.row.roleName + '?'" />
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="configAuthPage.total > 0"
            :total="configAuthPage.total"
            v-model:page="configAuthPage.roleParams.pageNum"
            v-model:limit="configAuthPage.roleParams.pageSize"
            @pagination="getRoleAuthList"
          />
        </el-tab-pane>
        <el-tab-pane label="岗位授权" name="05">
          <el-form :model="configAuthPage.postParams" :inline="true" label-width="100px">
            <el-form-item label="岗位名称：">
              <el-input v-model="configAuthPage.postParams.postNameLike" clearable size="default" style="width: 200px" />
            </el-form-item>
            <el-form-item>
              <search-button @click="handleAuthQuery" />
              <reset-button @click="resetAuthQuery" />
            </el-form-item>
          </el-form>
          <br />
          <el-row :gutter="10" class="mb8">
            <add-button @click="openAuthDialog" text="选择" />
            <delete-button @click="handleAuthDeleteBatch" :disabled="configAuthPage.selectAuthObjectList.length == 0" text="删除"></delete-button>
          </el-row>
          <el-table :data="configAuthPage.authPostDataList" @selection-change="handleAuthSelectionChange" border>
            <el-table-column type="selection" width="55" />
            <el-table-column label="数据权限范围" align="center" prop="dataScope" min-width="120">
              <template #default="scope">
                {{ selectDictLabel(dataScopeOptions, scope.row.dataScope) }}
              </template>
            </el-table-column>
            <el-table-column label="岗位名称" align="center" prop="postName" min-width="120" />
            <el-table-column label="岗位类型" align="center" prop="postCode" min-width="120" />
            <el-table-column label="状态" align="center" min-width="120">
              <template #default="scope">
                <el-tag :type="scope.row.status === 'Y' ? 'success' : 'danger'" disable-transitions>
                  {{ scope.row.status === 'Y' ? '正常' : '停用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" min-width="100" fixed="right">
              <template #default="scope">
                <text-delete-button @click="handleAuthDelete(scope.row)" :title="'是否确认删除' + scope.row.postName + '?'" />
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="configAuthPage.total > 0"
            :total="configAuthPage.total"
            v-model:page="configAuthPage.postParams.pageNum"
            v-model:limit="configAuthPage.postParams.pageSize"
            @pagination="getPostAuthList"
          />
        </el-tab-pane>
      </el-tabs>
      <br />
      <span style="color: red">
        注：开启授权后，仅以上清单中 [人员] 或 [部门下人员] 或 [公司下人员] 或 [角色下人员] 或 [岗位下人员] 方可调用模型接口， 如果启用授权且所有清单为空则等同于无权限
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="configAuthPage.open = false">关 闭</el-button>
        </div>
      </template>
      <drag-dialog v-model="configAuthPage.authDialogParams.open" :title="configAuthPage.authDialogParams.title" @close="cancelAuthDialog"
        width="50%" align-center>
        <el-form :model="configAuthPage.dataParams" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="权限范围：" prop="dataScope">
                <el-select v-model="configAuthPage.dataParams.dataScope" @change="handleDataScopeSelect">
                  <el-option v-for="dict in dataScopeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="人员字段名：" prop="fieldAlias" v-if="configAuthPage.dataParams.dataScope === '08'">
                <el-input v-model="configAuthPage.dataParams.fieldAlias" />
              </el-form-item>
              <el-form-item label="部门字段名：" prop="fieldAlias"
                v-if="configAuthPage.dataParams.dataScope === '03' || configAuthPage.dataParams.dataScope === '06' || configAuthPage.dataParams.dataScope === '07'
                || configAuthPage.dataParams.dataScope === '11' || configAuthPage.dataParams.dataScope === '12'">
                <el-input v-model="configAuthPage.dataParams.fieldAlias" />
              </el-form-item>
              <el-form-item label="公司字段名：" prop="fieldAlias"
                v-if="configAuthPage.dataParams.dataScope === '02' || configAuthPage.dataParams.dataScope === '04' || configAuthPage.dataParams.dataScope === '05' 
                || configAuthPage.dataParams.dataScope === '09' || configAuthPage.dataParams.dataScope === '10'">
                <el-input v-model="configAuthPage.dataParams.fieldAlias" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="指定公司：" prop="companyIds" v-if="configAuthPage.dataParams.dataScope === '02'">
            <el-tree-select
              v-model="configAuthPage.selectCompanyIds"
              :data="companyOptions"
              :props="defaultProps"
              multiple
              :render-after-expand="false"
              show-checkbox
              check-strictly
              check-on-click-node
              clearable
            />
          </el-form-item>
          <el-form-item label="指定部门：" prop="deptIds" v-if="configAuthPage.dataParams.dataScope === '03'">
            <el-tree-select
              v-model="configAuthPage.selectDeptIds"
              :data="deptOptions"
              :props="defaultProps"
              multiple
              :render-after-expand="false"
              show-checkbox
              check-strictly
              check-on-click-node
              clearable
            />
          </el-form-item>
          <el-row :gutter="10" style="margin: 0 0 5px 0">
            <add-button @click="selectAuthInfo" text="选择" />
          </el-row>
        </el-form>
        <!-- 人员授权表格 -->
        <el-table v-show="configAuthPage.dataParams.authType === '01'" :data="configAuthPage.authDialogParams.authObjects" border max-height="500px">
          <el-table-column label="登录名" align="center" prop="loginName" min-width="120" />
          <el-table-column label="用户姓名" align="center" prop="userName" min-width="120" />
          <el-table-column label="公司/部门" align="center" min-width="120">
            <template #default="scope">
              {{ (scope.row.companyName || '-') + ' / ' + (scope.row.deptName || '-') }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="100" fixed="right">
            <template #default="scope">
              <text-button text="删除" @click="configAuthPage.authDialogParams.authObjects
              .splice(configAuthPage.authDialogParams.authObjects.findIndex(obj => obj.userId === scope.row.userId), 1)" />
            </template>
          </el-table-column>
        </el-table>
        <!-- 部门授权表格 -->
        <el-table v-show="configAuthPage.dataParams.authType === '02'" :data="configAuthPage.authDialogParams.authObjects" border max-height="500px">
          <el-table-column label="部门名称" align="center" prop="deptName" min-width="120" />
          <el-table-column label="部门编码" align="center" prop="deptCode" min-width="120" />
          <el-table-column label="简称" align="center" prop="deptShortname" min-width="120" />
          <el-table-column label="操作" align="center" min-width="100" fixed="right">
            <template #default="scope">
              <text-button text="删除" @click="configAuthPage.authDialogParams.authObjects
              .splice(configAuthPage.authDialogParams.authObjects.findIndex(obj => obj.deptId === scope.row.deptId), 1)" />
            </template>
          </el-table-column>
        </el-table>
        <!-- 公司授权表格 -->
        <el-table v-show="configAuthPage.dataParams.authType === '03'" :data="configAuthPage.authDialogParams.authObjects" border max-height="500px">
          <el-table-column label="公司名称" align="center" prop="companyName" min-width="120" />
          <el-table-column label="公司编码" align="center" prop="companyCode" min-width="120" />
          <el-table-column label="简称" align="center" prop="companyShortname" min-width="120" />
          <el-table-column label="操作" align="center" min-width="100" fixed="right">
            <template #default="scope">
              <text-button text="删除" @click="configAuthPage.authDialogParams.authObjects
              .splice(configAuthPage.authDialogParams.authObjects.findIndex(obj => obj.companyId === scope.row.companyId), 1)" />
            </template>
          </el-table-column>
        </el-table>
        <!-- 角色授权表格 -->
        <el-table v-show="configAuthPage.dataParams.authType === '04'" :data="configAuthPage.authDialogParams.authObjects" border max-height="500px">
          <el-table-column label="角色名称" align="center" prop="roleName" min-width="120" />
          <el-table-column label="角色类型" prop="roleType" align="center" min-width="100">
            <template #default="scope">
              <el-tooltip
                v-if="scope.row.roleType === '0'"
                content="【系统内置】授权后可拥有所有菜单所有按钮权限"
                placement="right-start"
                effect="light"
              >
                <el-tag type="danger">超级角色</el-tag>
              </el-tooltip>
              <el-tooltip
                v-else-if="scope.row.roleType === '1'"
                placement="right-start"
                effect="light"
              >
                <template #content>
                  <div
                  >【系统内置】只有配置类型角色授权后才可以做系统的配置管理<br />配置管理包括角色、菜单、字典、参数和ZCache等管理权限</div
                  >
                </template>
                <el-tag type="warning">配置角色</el-tag>
              </el-tooltip>
              <el-tooltip
                v-else-if="scope.row.roleType === '2'"
                placement="right-start"
                effect="light"
              >
                <template #content>
                  <div
                  >用于实际业务系统的功能应用操作<br />即使进行菜单按钮授权也无法操作以上配置管理功能</div
                  >
                </template>
                <el-tag type="success" effect="light">应用角色</el-tag>
              </el-tooltip>
              <el-tag v-else>{{ scope.row.roleType }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="角色权限字符串" align="center" prop="roleKey" min-width="120" />
          <el-table-column label="操作" align="center" min-width="100" fixed="right">
            <template #default="scope">
              <text-button text="删除" @click="configAuthPage.authDialogParams.authObjects
              .splice(configAuthPage.authDialogParams.authObjects.findIndex(obj => obj.roleId === scope.row.roleId), 1)" />
            </template>
          </el-table-column>
        </el-table>
        <!-- 岗位授权表格 -->
        <el-table v-show="configAuthPage.dataParams.authType === '05'" :data="configAuthPage.authDialogParams.authObjects" border max-height="500px">
          <el-table-column label="岗位名称" align="center" prop="postName" min-width="120" />
          <el-table-column label="岗位类型" align="center" prop="postCode" min-width="120" />
          <el-table-column label="操作" align="center" min-width="100" fixed="right">
            <template #default="scope">
              <text-button text="删除" @click="configAuthPage.authDialogParams.authObjects
              .splice(configAuthPage.authDialogParams.authObjects.findIndex(obj => obj.postId === scope.row.postId), 1)" />
            </template>
          </el-table-column>
        </el-table>
        <template #footer>
          <dialog-footer @ok="submitAuthDialog" @cancel="cancelAuthDialog" />
        </template>
        <OrgPicker ref="orgPicker" @ok="doSelected" :selected="configAuthPage.authDialogParams.authObjects" />
        <DeptPicker ref="deptPicker" @ok="doSelected" :selected="configAuthPage.authDialogParams.authObjects" />
        <CompanyPicker ref="companyPicker" @ok="doSelected" :selected="configAuthPage.authDialogParams.authObjects" />
        <RolePicker ref="rolePicker" @ok="doSelected" :selected="configAuthPage.authDialogParams.authObjects" />
        <JobPicker ref="jobPicker" @ok="doSelected" :selected="configAuthPage.authDialogParams.authObjects" />
      </drag-dialog>
    </drag-dialog>

    <!-- 迁入对话框 -->
    <drag-dialog
      :title="upload.title"
      :close-on-click-modal="false"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".zip"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            Tips：迁入迁出主要用于多环境间数据传递，因此不建议用户对迁出的包进行修改
            <div class="el-upload__tip" style="color: red">
              提示：仅允许上传“zip”格式文件！
            </div>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <dialog-footer @ok="submitFileForm" @cancel="cancelUpload" />
      </template>
    </drag-dialog>
  </div>
</template>

<script>
import { roleDeptTreeselect, roleCompanyTreeselect } from '@base/api/base/role'
import {
  search,
  insertMdaTableInfo,
  delMdaTableInfoByIds,
  selectMdaTableInfoById,
  refreshColumnList,
  updateMdaTableInfo,
  getDatasource,
  getDataTableListById,
  getColumnList,
  updateIsDisabledById,
  getEnableAuthByTableName,
  searchAuthUser,
  searchAuthDept,
  searchAuthCompany,
  searchAuthRole,
  searchAuthPost,
  insertAuthInfo,
  deleteAuthInfo,
  saveEnableAuth,
  getAvailableSubModels,
  getSubModelColumns,
  saveSubModelRelations,
  getLinkedSubModels
} from '@uni/api/uni/mda/table/info';
import { debounceWrapper } from '@/utils/zmids';
import YesNoTag from '@/components/Zmids/YesNoTag/index.vue';
import ResetButton from '@/components/Zmids/Buttons/ResetButton.vue';
import CompanyPicker from '@/components/Zmids/CompanyName/index.vue';
import OrgPicker from '@/components/Zmids/OrgPicker/index.vue';
import JobPicker from '@/components/Zmids/JobPicker/index.vue';
import DeptPicker from '@/components/Zmids/DepartmentPicker/index.vue';
import RolePicker from '@/components/Zmids/RolePicker/index.vue';
import { getToken } from '@/utils/auth';
import defaultSettings from '@/settings'

export default {
  // 此处的名字需要与菜单中Path一致，否则多Tab页切换时会刷新
  name: 'UniMdaTableInfo',
  components: { RolePicker, DeptPicker, JobPicker, OrgPicker, CompanyPicker, 'yes-no-tag': YesNoTag, ResetButton },
  data() {
    return {
      subModelDialog: {
        visible: false,
        title: '子模型关联管理'
      },
      subModelRelations: [], // 关联关系临时数据
      allSubModels: [],       // 全部子模型列表
      selectedSubModels: new Set(), // 已选子模型ID集合
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      dataList: [],
      // 模型状态的固定字典选项列表
      isEnableOptions: [
        { dictValue: 'Y', dictLabel: '启用' },
        { dictValue: 'N', dictLabel: '禁用' }
      ],
      // 实体列表
      formEntityList: [],
      // 数据源选择列表
      dataSourceOptions: [],
      // 数据权限选择列表
      dataScopeOptions: [],
      // 部门下拉树
      deptOptions: [],
      // 公司下拉树
      companyOptions: [],
      // 默认下拉框属性配置规则
      defaultProps: {
        value: 'value',
        label: 'name',
        children: 'children',
        disabled: 'disabled'
      },
      // 配置授权页面
      configAuthPage: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderBy: 'update_time',
        sortDirect: 'DESC',
        // 表名
        tableNameLike: '',
        // 描述
        descriptionLike: '',
        // 请求路径
        requestMappingLike: '',
        // 模型状态
        isEnable: ''
      },
      editForm: {
        // 控制 dialog
        open: false,
        // 弹出层标题
        title: '',
        // 是否修改操作
        isModify: false,
        // 表单参数
        data: {},
        // 规则
        rules: {
          // 数据源
          datasourceCode: [
            { required: true, message: '数据源不可以为空', trigger: 'blur' },
            { min: 1, max: 64, message: '数据源的长度最多 64 个字符', trigger: 'blur' }
          ],
          // 表名
          tableName: [
            { required: true, message: '表名不可以为空', trigger: 'blur' },
            { min: 1, max: 64, message: '表名的长度最多 64 个字符', trigger: 'blur' }
          ],
          // 描述
          description: [
            { required: true, message: '描述不可以为空', trigger: 'blur' },
            { min: 1, max: 64, message: '描述的长度最多 64 个字符', trigger: 'blur' }
          ],
          // 是否主实体
          // isPrimary: [
          //   { required: true, message: '是否主实体不可以为空', trigger: 'blur' }
          // ],
          // 请求路径
          requestMapping: [
            { required: true, message: '请求路径不可以为空', trigger: 'blur' },
            { min: 1, max: 128, message: '描述的长度最多 128 个字符', trigger: 'blur' }
          ]
        }
      },
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '模型接口迁入',
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { [defaultSettings.tokenName]: 'Bearer ' + getToken() },
        // 上传的地址
        url: import.meta.env.VITE_APP_BASE_API + '/uni/mda/table/info/importZip'
      },
    };
  },
  computed: {
    filteredSubModels() {
      const exists = this.subModelRelations.map(item=>item.subTableId)
      const list = this.allSubModels.map(item => {
            if(exists.indexOf(item.tableId) > -1){
              item.disabled = true
            }else{
              item.disabled = false
            }
            return item
          }
      )
      console.log('list',list)
      return list
    }
  },
  created() {
    this.getDicts('sys_data_scope').then((response) => {
      this.dataScopeOptions = response.data
    })
    // 初始化数据权限参数
    this.initConfigAuthPage();
    // 查询列表
    this.getList();
    // 获取数据源选择列表
    this.getDataSourceOptions();
  },
  methods: {
    handleExport: debounceWrapper( function(row) {
      this.downloadUrl('/uni/mda/table/info/exportZip/' + row.tableName, undefined)
    }),

    // 迁入
    handleImport: debounceWrapper(function () {
      this.upload.open = true
    }),
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess: debounceWrapper(function (response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.msg, '迁入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    }),
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 取消上传
    cancelUpload() {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
    },

    // 打开关联子模型弹窗
    async handleRelateSubModel(row) {
      this.editForm.data.tableId = row.tableId;
      this.subModelDialog.visible = true;

      try {
        // 优先查询已关联数据
        const { data: linkedData } = await getLinkedSubModels({
          tableId: row.tableId
        });

        // 如果有历史数据则回填
        if (linkedData && linkedData.length > 0) {
          this.subModelRelations = linkedData.map(item => ({
            subTableId: item.subTableId,
            relationField: item.relationField,
            tableName: item.tableName,
            fieldOptions: [] // 先置空，后续通过字段查询填充
          }));
          console.log("subModelRelations", this.subModelRelations)

          // 更新已选集合
          this.selectedSubModels = new Set(
              linkedData.map(item => item.subTableId)
          );

          // 异步加载每个子模型的字段选项
          await Promise.all(this.subModelRelations.map(async (relation, index) => {
            const { data: fields } = await getSubModelColumns({
              tableId: relation.subTableId
            });
            this.subModelRelations.splice(index, 1, {
              ...relation,  // 保留已有属性（含tableName）
              fieldOptions: fields
            });
          }));
        } else {
          // 无数据时初始化空列表
          this.subModelRelations = [];
          this.selectedSubModels.clear();
        }

        // 获取所有可用子模型（排除已选和自身）
        const { data: allSubModels } = await getAvailableSubModels({
          tableId: row.tableId,
          datasourceCode: row.datasourceCode
        });
        this.allSubModels = allSubModels;

      } catch (error) {
        console.error('数据加载失败:', error);
        this.$message.error('数据加载失败');
        this.subModelDialog.visible = false;
      }
    },

    // 添加关联行
    addSubModelRow() {
      this.subModelRelations.push({
        subTableId: null,
        relationField: null,
        fieldOptions: []
      })
    },

    // 删除关联行
    removeSubModelRow(index) {
      const removed = this.subModelRelations.splice(index, 1)[0]
      if (removed.subTableId) {
        this.selectedSubModels.delete(removed.subTableId)
      }
    },

    // 子模型选择变化时
    async handleSubModelChange(subTableId, index) {
      // 清除旧值
      this.subModelRelations[index].relationField = null

      // 获取字段列表（需替换实际接口）
      const param = {
        tableId:subTableId
      }
      const { data } = await getSubModelColumns(param)
      this.subModelRelations[index].fieldOptions = data

      // 更新已选集合
      this.selectedSubModels.add(subTableId)
    },

    // 保存关联关系
    async saveSubModelRelation() {
      try {
        // 过滤有效数据
        const validData = this.subModelRelations.filter(item =>
            item.subTableId && item.relationField
        )
        const subTableIds = validData.map(item => item.subTableId).join(',');
        const relationFields = validData.map(item => item.relationField).join(',');
        // 调用保存接口（需替换实际接口）
        await saveSubModelRelations({
          tableId: this.editForm.data.tableId,
          subTableIds: subTableIds,
          relationFields: relationFields
        })

        this.$message.success('保存成功')
        this.subModelDialog.visible = false
      } catch (error) {
        console.error('Error:', error);
        this.$message.error('保存失败')
      }
    },
    // 查询列表
    getList: debounceWrapper(function () {
      this.loading = true;
      search(this.queryParams).then((response) => {
        this.dataList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    }),
    /** 查询部门机构树结构 */
    getDeptTreeselect() {
      roleDeptTreeselect().then((response) => {
        this.deptOptions = response.data.orgs;
        this.setDisabledForTypeC(this.deptOptions);
        this.editValueField(this.deptOptions);
      })
    },
    /** 查询公司机构树结构 */
    getCompanyTreeselect() {
      roleCompanyTreeselect().then((response) => {
        this.companyOptions = response.data.companys;
        this.editValueField(this.companyOptions);
      })
    },
    // 部门下拉树中不允许选择公司
    setDisabledForTypeC(nodes) {
      nodes.forEach(node => {
        // 如果节点的 params.type === 'C'，设置 disabled 为 true
        if (node.params && node.params.type === 'C') {
          node.disabled = true;
        }
        // 如果节点有子节点 (children)，递归调用函数处理子节点
        if (node.children && Array.isArray(node.children)) {
          this.setDisabledForTypeC(node.children);
        }
      });
    },
    // 递归解决树中存在的value值与组件不兼容问题
    editValueField(nodes) {
      nodes.forEach(node => {
        node.value = node.id; // 修改冲突的 value 字段
        if (node.children) {
          this.editValueField(node.children);
        }
      });
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置按钮操作
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 表单重置
    reset() {
      this.editForm.isModify = false;
      this.editForm.data = {
        // 主键ID
        tableId: undefined,
        // 数据源编码
        datasourceCode: undefined,
        // 表名
        tableName: '',
        // 描述
        description: '',
        // // 是否主实体
        // isPrimary: undefined,
        // 仓库名
        repository: '',
        // 请求路径
        requestMapping: '',
        // 类名
        className: '',
        // 类包名
        classPackage: '',
        // 子模型ID
        subTableId: undefined,
        // 模型状态
        isEnable: '',
        // 创建者
        createBy: '',
        // 创建时间
        createTime: undefined,
        // 更新者
        updateBy: '',
        // 更新时间
        updateTime: undefined,
        // 备注
        remark: ''
      };
      // 重置字段校验
      this.$refs.formRef && this.$refs.formRef.clearValidate();
      this.resetForm('formRef');
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      // 所有选中的ID
      this.ids = selection.map((item) => item.tableId);
      // 激活多选删除
      this.multiple = !selection.length;
    },
    // 新增按钮操作
    handleAdd() {
      this.reset();
      this.editForm.open = true;
      this.editForm.isModify = false;
      this.editForm.title = '新增模型表定义';
    },
    // 初始化配置授权页面参数
    initConfigAuthPage() {
      this.configAuthPage = {
        open: false,
        title: '数据权限配置',
        enableAuth: 'N',
        total: 0,
        authUserDataList: [], // 人员授权列表数据
        authDeptDataList: [], // 部门授权列表数据
        authCompanyDataList: [], // 公司授权列表数据
        authRoleDataList: [], // 角色授权列表数据
        authPostDataList: [], // 岗位授权列表数据
        selectAuthObjectList: [], // 多选列表
        selectDeptIds: [], // 选中的指定部门列表
        selectCompanyIds: [], // 选中的指定公司列表
        // 授权通用参数map
        dataParams: {
          tableName: '',
          authType: '',
          dataScope: '', // 权限范围
          fieldAlias: '', // 字段别名
          companyIds: '', // 指定公司
          deptIds: '', // 指定部门
          authObjectIds: ''
        },
        // 授权弹窗参数map
        authDialogParams: {
          open: false,
          title: '',
          authObjects: [],
        },
        // 人员授权参数
        userParams: {
          pageNum: 1,
          pageSize: 10,
          tableName: '',
          authType: '01',
          loginNameLike: '',
          userNameLike: ''
        },
        // 部门授权参数
        deptParams: {
          pageNum: 1,
          pageSize: 10,
          tableName: '',
          authType: '02',
          deptNameLike: ''
        },
        // 公司授权参数
        companyParams: {
          pageNum: 1,
          pageSize: 10,
          tableName: '',
          authType: '03',
          companyNameLike: ''
        },
        // 角色授权参数
        roleParams: {
          pageNum: 1,
          pageSize: 10,
          tableName: '',
          authType: '04',
          roleNameLike: ''
        },
        // 岗位授权参数
        postParams: {
          pageNum: 1,
          pageSize: 10,
          tableName: '',
          authType: '05',
          postNameLike: ''
        },
      }
    },
    // 数据权限按钮
    handleAuth: debounceWrapper(function (row) {
      this.loading = true;
      this.configAuthPage.dataParams.tableName = row.tableName;
      // 判断该mdaTable授权是否打开
      getEnableAuthByTableName(this.configAuthPage.dataParams.tableName).then(res => {
        this.configAuthPage.enableAuth = res.data;
        // 如果打开，进行数据查询
        if (this.configAuthPage.enableAuth === "Y"){
          this.getUserAuthList();
          this.getDeptTreeselect();
          this.getCompanyTreeselect();
        }
      })
      this.configAuthPage.open = true;
      this.loading = false;
    }),
    // 获取人员授权列表初始信息
    getUserAuthList(){
      // 初始授权列表为人员授权列表01
      this.configAuthPage.dataParams.authType = "01";
      this.configAuthPage.userParams.tableName = this.configAuthPage.dataParams.tableName;
      searchAuthUser(this.configAuthPage.userParams).then(res => {
        this.configAuthPage.authUserDataList = res.data.list;
        this.configAuthPage.total = res.data.total;
      });
    },

    // 获取部门授权列表初始信息
    getDeptAuthList(){
      this.configAuthPage.deptParams.tableName = this.configAuthPage.dataParams.tableName;
      searchAuthDept(this.configAuthPage.deptParams).then(res => {
        this.configAuthPage.authDeptDataList = res.data.list;
        this.configAuthPage.total = res.data.total;
      });
    },

    // 获取公司授权列表初始信息
    getCompanyAuthList(){
      this.configAuthPage.companyParams.tableName = this.configAuthPage.dataParams.tableName;
      searchAuthCompany(this.configAuthPage.companyParams).then(res => {
        this.configAuthPage.authCompanyDataList = res.data.list;
        this.configAuthPage.total = res.data.total;
      });
    },

    // 获取角色授权列表初始信息
    getRoleAuthList(){
      this.configAuthPage.roleParams.tableName = this.configAuthPage.dataParams.tableName;
      searchAuthRole(this.configAuthPage.roleParams).then(res => {
        this.configAuthPage.authRoleDataList = res.data.list;
        this.configAuthPage.total = res.data.total;
      });
    },

    // 获取岗位授权列表初始信息
    getPostAuthList(){
      this.configAuthPage.postParams.tableName = this.configAuthPage.dataParams.tableName;
      searchAuthPost(this.configAuthPage.postParams).then(res => {
        this.configAuthPage.authPostDataList = res.data.list;
        this.configAuthPage.total = res.data.total;
      });
    },

    // 配置授权页面关闭
    cancelConfigAuth(){
      this.initConfigAuthPage()
    },

    // 切换开启/关闭授权回调
    handleEnableAuth(value){
      // 构建方法参数
      const openParams = {
        tableName: this.configAuthPage.dataParams.tableName,
        enableAuth: '',
        withDelete: ''
      };
      if (value === 'Y'){
        this.$confirm('此操作将开启授权, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.configAuthPage.enableAuth = value;
          openParams.enableAuth = value;
          openParams.withDelete = 'N';
          saveEnableAuth(openParams).then(res => {
            this.getUserAuthList(); // 开启后初始化人员授权列表
            this.$message({
              type: 'success',
              message: '开启成功!'
            });
          });
        }).catch(() => {
          this.configAuthPage.dataParams.authType = '';
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
      }
      if (value === 'N'){
        this.$confirm('此操作将关闭授权，是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$confirm('是否保留已有的授权信息？', '提示', {
            confirmButtonText: '保留',
            cancelButtonText: '不保留',
            type: 'warning'
          }).then(() => {
            this.configAuthPage.enableAuth = value;
            this.configAuthPage.dataParams.authType = '';
            openParams.enableAuth = value;
            openParams.withDelete = 'N';
            saveEnableAuth(openParams).then(res => {
              this.$message({
                type: 'success',
                message: '关闭成功，保留已有的授权信息'
              });
            });
          }).catch(() => {
            this.configAuthPage.enableAuth = value;
            this.configAuthPage.dataParams.authType = '';
            openParams.enableAuth = value;
            openParams.withDelete = 'Y';
            saveEnableAuth(openParams).then(res => {
              this.$message({
                type: 'success',
                message: '关闭成功，清空已有的授权信息'
              });
              // 将数据全部初始化
              this.initConfigAuthPage();
            });
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消关闭'
          });
        });
      }
    },

    // 切换授权类型回调
    handleAuthType(tab, event) {
      // 使用 Vue.nextTick 等待 DOM 和数据更新完毕后再执行逻辑
      this.$nextTick(() => {
        // 清空选择的id列表
        this.configAuthPage.selectAuthObjectList = [];
        this.configAuthPage.dataParams.authObjectIds = '';
        this.resetAuthQuery();
      });
    },

    // 通用授权列表查询
    handleAuthQuery: debounceWrapper(function() {
      if (this.configAuthPage.dataParams.authType === "01"){
        this.getUserAuthList();
      }
      if (this.configAuthPage.dataParams.authType === "02"){
        this.getDeptAuthList();
      }
      if (this.configAuthPage.dataParams.authType === "03"){
        this.getCompanyAuthList();
      }
      if (this.configAuthPage.dataParams.authType === "04"){
        this.getRoleAuthList();
      }
      if (this.configAuthPage.dataParams.authType === "05"){
        this.getPostAuthList();
      }
    }),

    // 通用授权列表多选回调
    handleAuthSelectionChange(value){
      this.configAuthPage.selectAuthObjectList = value;
    },

    // 打开authDialog弹框
    openAuthDialog: debounceWrapper(function() {
      if (this.configAuthPage.dataParams.authType === "01"){
        this.configAuthPage.authDialogParams.title = "授权配置-选择人员";
      }
      if (this.configAuthPage.dataParams.authType === "02"){
        this.configAuthPage.authDialogParams.title = "授权配置-选择部门";
      }
      if (this.configAuthPage.dataParams.authType === "03"){
        this.configAuthPage.authDialogParams.title = "授权配置-选择公司";
      }
      if (this.configAuthPage.dataParams.authType === "04"){
        this.configAuthPage.authDialogParams.title = "授权配置-选择角色";
      }
      if (this.configAuthPage.dataParams.authType === "05"){
        this.configAuthPage.authDialogParams.title = "授权配置-选择岗位";
      }
      this.configAuthPage.authDialogParams.open = "true";
    }),

    // 处理dataScope下拉框选中时间
    handleDataScopeSelect(value){
      // 仅本人数据
      if (value === '08'){
        this.configAuthPage.dataParams.fieldAlias = "USER_ID";
      }
      // 公司数据
      if (value === '02' || value === '04' || value === '05' || value === '09' || value === '10'){
        this.configAuthPage.dataParams.fieldAlias = "COMPANY_ID";
      }
      // 部门数据
      if (value === '03' || value === '06' || value === '07' || value === '11' || value === '12'){
        this.configAuthPage.dataParams.fieldAlias = "DEPT_ID";
      }
    },

    // 通用打开选择人员弹框
    selectAuthInfo: debounceWrapper(function(){
      if (this.configAuthPage.dataParams.authType === "01"){
        this.$refs.orgPicker.show();
      }
      if (this.configAuthPage.dataParams.authType === "02"){
        this.$refs.deptPicker.show();
      }
      if (this.configAuthPage.dataParams.authType === "03"){
        this.$refs.companyPicker.show();
      }
      if (this.configAuthPage.dataParams.authType === "04"){
        this.$refs.rolePicker.show();
      }
      if (this.configAuthPage.dataParams.authType === "05"){
        this.$refs.jobPicker.show();
      }
    }),

    // 选择授权信息后回调
    doSelected(list){
      this.configAuthPage.authDialogParams.authObjects = list;
    },

    // 提交authDialog弹框
    submitAuthDialog: debounceWrapper(function() {
      if (this.configAuthPage.dataParams.authType === '01') {
        // 使用 map 提取每个 user 的 userId
        const userIds = this.configAuthPage.authDialogParams.authObjects.map(user => user.userId);
        // 将 userId 数组转换为逗号分隔的字符串
        this.configAuthPage.dataParams.authObjectIds = userIds.join(',');
      }
      if (this.configAuthPage.dataParams.authType === '02'){
        const deptIds = this.configAuthPage.authDialogParams.authObjects.map(dept => dept.deptId);
        this.configAuthPage.dataParams.authObjectIds = deptIds.join(',');
      }
      if (this.configAuthPage.dataParams.authType === '03'){
        const companyIds = this.configAuthPage.authDialogParams.authObjects.map(company => company.companyId);
        this.configAuthPage.dataParams.authObjectIds = companyIds.join(',');
      }
      if (this.configAuthPage.dataParams.authType === '04'){
        const roleIds = this.configAuthPage.authDialogParams.authObjects.map(role => role.roleId);
        this.configAuthPage.dataParams.authObjectIds = roleIds.join(',');
      }
      if (this.configAuthPage.dataParams.authType === '05'){
        const postIds = this.configAuthPage.authDialogParams.authObjects.map(post => post.postId);
        this.configAuthPage.dataParams.authObjectIds = postIds.join(',');
      }
      // 将deptIds和companyIds转成字符串
      this.configAuthPage.dataParams.deptIds = this.configAuthPage.selectDeptIds.join(',');
      this.configAuthPage.dataParams.companyIds = this.configAuthPage.selectCompanyIds.join(',');
      // 插入列表信息
      insertAuthInfo(this.configAuthPage.dataParams).then(res => {
        this.$message.success("授权信息添加成功，您可在列表中查看相关详情！");
        // 插入成功后清空参数列表
        this.cancelAuthDialog();
        this.handleAuthQuery();
      })
    }),

    // 关闭authDialog弹框
    cancelAuthDialog: debounceWrapper(function() {
      this.configAuthPage.authDialogParams.open = false;
      this.configAuthPage.authDialogParams.title = '';
      this.configAuthPage.authDialogParams.authObjects = [];
      this.configAuthPage.dataParams.dataScope = '';
      this.configAuthPage.dataParams.fieldAlias = '';
      this.configAuthPage.dataParams.companyIds = [];
      this.configAuthPage.dataParams.deptIds = [];
      this.configAuthPage.dataParams.authObjectIds = '';
    }),

    // 通用授权列表参数重置
    resetAuthQuery(){
      if (this.configAuthPage.dataParams.authType === '01') {
        this.configAuthPage.userParams = {
          pageNum: 1,
          pageSize: 10,
          tableName: '',
          authType: '01',
          loginNameLike: '',
          userNameLike: ''
        };
        this.getUserAuthList();
      }
      if (this.configAuthPage.dataParams.authType === '02') {
        this.configAuthPage.deptParams = {
          pageNum: 1,
          pageSize: 10,
          tableName: '',
          authType: '02',
          deptNameLike: ''
        };
        this.getDeptAuthList();
      }
      if (this.configAuthPage.dataParams.authType === '03') {
        this.configAuthPage.companyParams = {
          pageNum: 1,
          pageSize: 10,
          tableName: '',
          authType: '03',
          companyNameLike: ''
        };
        this.getCompanyAuthList();
      }
      if (this.configAuthPage.dataParams.authType === '04') {
        this.configAuthPage.roleParams = {
          pageNum: 1,
          pageSize: 10,
          tableName: '',
          authType: '04',
          roleNameLike: ''
        };
        this.getRoleAuthList();
      }
      if (this.configAuthPage.dataParams.authType === '05') {
        this.configAuthPage.postParams = {
          pageNum: 1,
          pageSize: 10,
          tableName: '',
          authType: '05',
          postNameLike: ''
        };
        this.getPostAuthList();
      }
    },

    // 批量删除授权信息
    handleAuthDeleteBatch: debounceWrapper(function(){
      if (this.configAuthPage.dataParams.authType === '01'){
        // 使用 map 提取每个 user 的 userId
        const userIds = this.configAuthPage.selectAuthObjectList.map(user => user.userId);
        // 将 userId 数组转换为逗号分隔的字符串
        this.configAuthPage.dataParams.authObjectIds = userIds.join(',');
      }
      if (this.configAuthPage.dataParams.authType === '02'){
        const deptIds = this.configAuthPage.selectAuthObjectList.map(dept => dept.deptId);
        this.configAuthPage.dataParams.authObjectIds = deptIds.join(',');
      }
      if (this.configAuthPage.dataParams.authType === '03'){
        const companyIds = this.configAuthPage.selectAuthObjectList.map(company => company.companyId);
        this.configAuthPage.dataParams.authObjectIds = companyIds.join(',');
      }
      if (this.configAuthPage.dataParams.authType === '04'){
        const roleIds = this.configAuthPage.selectAuthObjectList.map(role => role.roleId);
        this.configAuthPage.dataParams.authObjectIds = roleIds.join(',');
      }
      if (this.configAuthPage.dataParams.authType === '05'){
        const postIds = this.configAuthPage.selectAuthObjectList.map(post => post.postId);
        this.configAuthPage.dataParams.authObjectIds = postIds.join(',');
      }

      // 批量删除
      deleteAuthInfo(this.configAuthPage.dataParams).then(res => {
        this.$message.success("删除成功！");
        // 清空选择列表
        this.configAuthPage.selectAuthObjectList = [];
        this.configAuthPage.dataParams.authObjectIds = '';
        this.handleAuthQuery();
      })
    }),

    // 删除授权信息
    handleAuthDelete: debounceWrapper(function(row) {
      if (this.configAuthPage.dataParams.authType === '01'){
        this.configAuthPage.dataParams.authObjectIds = row.userId;
      }
      if (this.configAuthPage.dataParams.authType === '02'){
        this.configAuthPage.dataParams.authObjectIds = row.deptId;
      }
      if (this.configAuthPage.dataParams.authType === '03'){
        this.configAuthPage.dataParams.authObjectIds = row.companyId;
      }
      if (this.configAuthPage.dataParams.authType === '04'){
        this.configAuthPage.dataParams.authObjectIds = row.roleId;
      }
      if (this.configAuthPage.dataParams.authType === '05'){
        this.configAuthPage.dataParams.authObjectIds = row.postId;
      }

      deleteAuthInfo(this.configAuthPage.dataParams).then(res => {
        this.$message.success("删除成功！");
        // 清空选择列表
        this.configAuthPage.dataParams.authObjectIds = '';
        this.handleAuthQuery();
      })
    }),

    // 禁/启用按钮操作
    handleEnableChange: debounceWrapper(function (row) {
      row.isEnable = row.isEnable == 'Y' ? 'N' : 'Y';
      updateIsDisabledById(row).then(() => {
        this.getList();
        this.msgSuccess('状态修改成功');
      });
    }),
    // 删除按钮操作
    handleDelete: debounceWrapper(function (row) {
      const deleteIds = row ? row.tableId : this.ids.join(',');
      delMdaTableInfoByIds(deleteIds)
        .then(() => {
          this.getList();
          this.msgSuccess('删除成功');
        });
    }),
    // 修改按钮操作
    handleUpdate: debounceWrapper(function (row) {
      this.reset();
      selectMdaTableInfoById(row.tableId).then((response) => {
        this.editForm.data = response.data;
        this.editForm.open = true;
        this.editForm.isModify = true;
        this.editForm.title = '修改模型表定义';
      });
    }),
    //数据源选择 选择建模-现有模板 - 下拉框
    getDataSourceOptions() {
      getDatasource().then((response) => {
        console.log('response.data', response.data);
        this.dataSourceOptions = response.data;
      });
    },
    // 获取实体
    getModelColumn() {
      if (this.editForm.data.datasourceCode != undefined) {
        getDataTableListById(this.editForm.data.datasourceCode).then((response) => {
          this.formEntityList = response.data;
        });
      }
    },
    // 选中数据源实体时触发
    handleSelectBranchCom() {
      // 带出描述信息
      const item = this.formEntityList.find((item) => item.dictValue == this.editForm.data.tableName);
      this.editForm.data.description = item.description;
      // 设置默认请求路径
      this.editForm.data.requestMapping = item.dictValue.replace(/_/g, '/');
      const params = {
        datasourceCode: this.editForm.data.datasourceCode,
        tableName: this.editForm.data.tableName
      };
      getColumnList(params).then((response) => {
        this.editForm.data.columns = response.data;
      });
    },
    // 刷新表信息
    refreshColumn: debounceWrapper(function () {
      const params = {
        datasourceCode: this.editForm.data.datasourceCode,
        tableId: this.editForm.data.tableId
      };
      refreshColumnList(params).then((res) => {
          if (res.code == '200') {
            selectMdaTableInfoById(this.editForm.data.tableId).then((response) => {
                this.editForm.data = response.data;
                this.$message.success('刷新成功!');
              }).catch((error) => {
                // 处理错误，例如:
                console.error(error);
                this.$message.error('刷新失败!');
              });
          }
        }).catch((error) => {
          // 处理 refreshColumnList 的错误
          console.error(error);
          this.$message.error('刷新列表失败!');
        });
    }),
    // 提交按钮
    submitForm: debounceWrapper(function () {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          // 创建者
          delete this.editForm.data.createBy;
          // 创建时间
          delete this.editForm.data.createTime;
          // 更新者
          delete this.editForm.data.updateBy;
          // 更新时间
          delete this.editForm.data.updateTime;

          const ifUpdate = this.editForm.isModify;
          const promise = ifUpdate ? updateMdaTableInfo(this.editForm.data) : insertMdaTableInfo(this.editForm.data);
          promise.then((response) => {
            if (response.data) {
              this.msgSuccess(ifUpdate ? '修改成功' : '新增成功');
              this.editForm.open = false;
              this.getList();
            }
          });
        }
      });
    }),
    // 取消按钮
    cancel() {
      this.editForm.open = false;
      this.reset();
    }
  }
};
</script>

<style lang="scss" scoped></style>
